package com.android.nodejs.livejs.activities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.adapters.MessageAdapter;
import com.android.nodejs.livejs.base.BaseFragment;
import com.android.nodejs.livejs.models.MyMessage;
import com.android.nodejs.livejs.utils.CommonUtil;

public class ChatFragment extends BaseFragment {

    private ListView mListView;
    private View mView;
    private MessageAdapter messageAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_chats, null);
        // register broad cast
        IntentFilter filterMessageChat = new IntentFilter("MESSAGE_CHAT");
        getActivity().registerReceiver(new MessageBroadCastReceiver(), filterMessageChat);
        return mView;
    }

    @Override
    public void inits() {
        // nothing
    }

    @Override
    public void initComponents(View view) {
        mListView = (ListView) view.findViewById(R.id.listChatting);
        messageAdapter = new MessageAdapter(getActivity(), new ArrayList<MyMessage>());
        mListView.setAdapter(messageAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapter, View v, int postion, long id) {
                //start Chat Activity
                Intent intentChat = new Intent();
                intentChat.setClass(getActivity(), ChatActivity.class);
                Bundle b = new Bundle();
                b.putSerializable("list_msgs", (Serializable) (((MyMessage) adapter.getAdapter().getItem(postion)).getMessage()));
                b.putSerializable("list_times", (Serializable) (((MyMessage) adapter.getAdapter().getItem(postion)).getTime()));
                b.putInt("group_id", ((MyMessage) mListView.getAdapter().getItem(postion)).getIdGroup());
                b.putInt("sender_id", ((MyMessage) mListView.getAdapter().getItem(postion)).getIdSender());
                b.putString("friend_full_name", ((MyMessage) mListView.getAdapter().getItem(postion)).getNameSender());
                b.putString("friend_avatar",
                        "http://profile.ak.fbcdn.net/hprofile-ak-ash3/c72.31.388.388/s160x160/69242_445766122158689_209300158_n.jpg");
                intentChat.putExtras(b);
                getActivity().startActivityForResult(intentChat, 101);
            }
        });
    }

    @Override
    public void addListenners() {
        // nothing
    }

    /** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                // list view chua co phan tu nao
                Bundle data = msg.getData();
                String message = data.getString("MESSAGE");
                String time = data.getString("TIME");
                int idGroup = data.getInt("GROUP_ID");
                int idSender = data.getInt("SENDER_ID");
                String senderName = data.getString("SENDER_NAME");
                if (!MyApplication.MSGS.containsKey(idGroup)) {
                    MyMessage myMsg = new MyMessage();
                    myMsg.setIdGroup(idGroup);
                    myMsg.setIdSender(idSender);
                    myMsg.setNameSender(senderName);
                    ArrayList<String> times = new ArrayList<String>();
                    times.add(time);
                    myMsg.setTime(times);
                    ArrayList<String> msgs = new ArrayList<String>();
                    msgs.add(message);
                    myMsg.setMessage(msgs);
                    MyApplication.MSGS.put(idGroup, myMsg);
                } else {
                    MyApplication.MSGS.get(idGroup).getMessage().add(message);
                    MyApplication.MSGS.get(idGroup).getTime().add(time);
                }
                Log.d("XXXXXXXxxxxxxxxXX", ""+idSender);

                // } else {
                // // vong lap check phan tu trung trong list view
                // int num = -1;
                // for (int i = 0; i < MyApplication.MSGS.size(); i++) {
                // if(idGroup ==
                // MyApplication.MSGS.get(idGroup).get(i).getIdGroup()) {
                // num = i;
                // break;
                // }
                // }
                // // neu khong trung (ko co item nao giong item muon them vao)
                // if(num == -1) {
                // myMsg = new MyMessage();
                // myMsg.setIdGroup(idGroup);
                // myMsg.setIdSender(idSender);
                // myMsg.setNameSender(nameSender);
                // myMsg.setTime(fr_time);
                // myMsg.setMessage(fr_msg);
                // listMessages.add(myMsg);
                // MyApplication.MSGS.put(idGroup, listMessages);
                // } else { // neu co item nay roi thi chi set lai msg
                // myMsg = new MyMessage();
                // myMsg.setIdGroup(idGroup);
                // myMsg.setIdSender(idSender);
                // myMsg.setNameSender(nameSender);
                // myMsg.setTime(fr_time);
                // myMsg.setMessage(fr_msg);
                // MyApplication.MSGS.set(num, myMsg);
                // }
                // }
                MyMessage myMsg = new MyMessage();
                myMsg.setIdGroup(idGroup);
                int index = messageAdapter.getPosition(myMsg);
                if (index >= 0 && index < messageAdapter.getCount()) {
                    messageAdapter.getItem(index).getMessage().add(message);
                    messageAdapter.getItem(index).getTime().add(time);
                } else {
                    myMsg.setIdSender(idSender);
                    myMsg.setNameSender(senderName);
                    ArrayList<String> times = new ArrayList<String>();
                    times.add(time);
                    myMsg.setTime(times);
                    ArrayList<String> msgs = new ArrayList<String>();
                    msgs.add(message);
                    myMsg.setMessage(msgs);
                    messageAdapter.add(myMsg);
                }
                messageAdapter.notifyDataSetChanged();
                mListView.setAdapter(messageAdapter);
            }
        }
    };

    /**
     * send message broadcast
     * 
     * @author vuvt
     * 
     */
    private class MessageBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("MESSAGE_CHAT".equals(intent.getAction())) {
                Log.d("yyyyyyyyyyyyyyyyyyy", "yyy");
                int idGroup = Integer.parseInt(intent.getStringExtra("idGroup"));
                MyApplication.GROUP_ID = intent.getStringExtra("idGroup");
                int idSender = Integer.parseInt(intent.getStringExtra("idSender"));
                String nameSender = intent.getStringExtra("nameSender");
                String m = intent.getStringExtra("msg");
                Message msg = toastHandler.obtainMessage(0);
                Bundle data = new Bundle();
                data.putString("MESSAGE", m);
                data.putString("TIME", CommonUtil.getSysTime());
                data.putInt("GROUP_ID", idGroup);
                data.putInt("SENDER_ID", idSender);
                data.putString("SENDER_NAME", nameSender);
                msg.setData(data);
                toastHandler.sendMessage(msg);
            }
        }
    }

}
